/**create by liuhua at 2020年10月22日 下午2:16:24**/
package com.star.aries.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.star.aries.utils.excel.FreezePaneHandler;

public class ExcelUtils {

  public static ResponseEntity<byte[]> exportExcel(String fileName, List<?> data, Class<?> c, List<String> includeFiled) throws UnsupportedEncodingException {
    WriteCellStyle headWriteCellStyle = new WriteCellStyle();
    // 背景设置为红色
//    headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
    WriteFont headWriteFont = new WriteFont();
    headWriteFont.setFontHeightInPoints((short) 12);
    headWriteCellStyle.setWriteFont(headWriteFont);
    headWriteCellStyle.setWrapped(false);
    // 内容的策略
    WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
    // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
//    contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
    // 背景绿色
//    contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
    WriteFont contentWriteFont = new WriteFont();
    // 字体大小
    contentWriteFont.setFontHeightInPoints((short) 12);
    contentWriteCellStyle.setWriteFont(contentWriteFont);

    HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ExcelWriterSheetBuilder excelWriterSheetBuilder = EasyExcel.write(bos, c).sheet("sheet1")
        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
        .registerWriteHandler(new FreezePaneHandler())
        .registerWriteHandler(horizontalCellStyleStrategy);
    if (null != includeFiled && !includeFiled.isEmpty()) {
      excelWriterSheetBuilder = excelWriterSheetBuilder.includeColumnFiledNames(includeFiled);
    }

    excelWriterSheetBuilder.doWrite(data);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName + ".xlsx", "utf-8"));
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

    return ResponseEntity.ok().headers(headers).contentLength(bos.toByteArray().length).body(bos.toByteArray());
  }

  public static ResponseEntity<byte[]> exportExcel(String fileName, List<?> data, Class<?> c, List<String> includeFiled, HorizontalCellStyleStrategy horizontalCellStyleStrategy) throws UnsupportedEncodingException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ExcelWriterSheetBuilder excelWriterSheetBuilder = EasyExcel.write(bos, c).sheet("sheet1").registerWriteHandler(new FreezePaneHandler()).registerWriteHandler(horizontalCellStyleStrategy);
    if (null != includeFiled && !includeFiled.isEmpty()) {
      excelWriterSheetBuilder = excelWriterSheetBuilder.includeColumnFiledNames(includeFiled);
    }

    excelWriterSheetBuilder.doWrite(data);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName + ".xlsx", "utf-8"));
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

    return ResponseEntity.ok().headers(headers).contentLength(bos.toByteArray().length).body(bos.toByteArray());
  }

  public static <T> List<T> importExcel(String path, Class<T> c) {
    return EasyExcel.read(path).head(c).sheet(0).doReadSync();
  }

  public static void createZipFile(OutputStream out, List<File> srcfile) throws IOException {
    ZipOutputStream zipOutputStream = new ZipOutputStream(out);
    byte[] buf = new byte[1024];
    for (int i = 0; i < srcfile.size(); i++) {
      File temp = srcfile.get(i);
      FileInputStream in = new FileInputStream(temp);
      zipOutputStream.putNextEntry(new ZipEntry(temp.getName()));
      int len;
      while ((len = in.read(buf)) > 0) {
        zipOutputStream.write(buf, 0, len);
      }
      zipOutputStream.closeEntry();
      in.close();
    }
    // 关闭输出流
    zipOutputStream.flush();
    zipOutputStream.close();
  }

  public static void downZipFile(HttpServletResponse response, String zipFileName, List<File> srcfile) throws IOException {
    zipFileName = URLEncoder.encode(zipFileName, "UTF-8");
    response.setContentType("application/octet-stream");
    response.setHeader("Connection", "close");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("Content-Disposition", "attachment; filename=" + zipFileName);
    OutputStream out = response.getOutputStream();
    createZipFile(out, srcfile);
    out.close();
  }
}
